package com.fw.ui.view.settings.usercontrol.bouser.event;

import static org.springframework.beans.factory.config.BeanDefinition.SCOPE_PROTOTYPE;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.fw.ui.bao.BOUserBAO;
import com.fw.ui.bao.MessageBAO;
import com.fw.ui.view.event.AbstractValueChangeListener;
import com.fw.ui.view.settings.usercontrol.bouser.CreateBOUserView;
import com.vaadin.data.Property.ValueChangeEvent;

@Component
@Scope(SCOPE_PROTOTYPE)
public class CreateBOUserUsernameValueChangeListener extends AbstractValueChangeListener {

    private static final long serialVersionUID = 1L;

    @Autowired
    private BOUserBAO bOUserBAO;
    @Autowired
    private MessageBAO messageBAO;

    @Override
    public boolean validate(ValueChangeEvent event) throws Exception {
	CreateBOUserView createBOUserView = (CreateBOUserView) this.getBasedComponent();
	createBOUserView.getRow1Validate().setVisible(false);
	createBOUserView.getLblUsernameValidateMessage().setValue("");
	createBOUserView.getTxtUsername().removeStyleName("v-textfield-error");
	boolean usernameValid = createBOUserView.getTxtUsername().isValid();
	if (!usernameValid) {
	    createBOUserView.getTxtUsername().addStyleName("v-textfield-error");
	    if (createBOUserView.getTxtUsername().getErrorMessage() != null) {
		createBOUserView.getLblUsernameValidateMessage().setValue(
			createBOUserView.getTxtUsername().getErrorMessage().getFormattedHtmlMessage());
	    }
	    createBOUserView.getRow1Validate().setVisible(true);
	} else {
	    Boolean isUnique = this.bOUserBAO.checkUniqueUsername(createBOUserView.getTxtUsername().getValue());
	    if (isUnique == null || !isUnique.booleanValue()) {
		createBOUserView.getTxtUsername().addStyleName("v-textfield-error");
		createBOUserView.getLblUsernameValidateMessage().setValue(
			this.messageBAO.getMessage("com.fw.ui.view.settings.usercontrol.bouser.CreateBOUserView.message.username.exist"));
		createBOUserView.getRow1Validate().setVisible(true);
	    }
	}
	return true;
    }

    @Override
    public void change(ValueChangeEvent event) throws Exception {
	// TODO Auto-generated method stub

    }

}
